<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 输出JSON格式数据
 * @author zxj
 * @access public
 * @param status(状态：bool),message(消息),data(数据),$isdebug(是否调试状态)
 */
if ( ! function_exists('json_output'))
{
	function json_output($data='',$message='',$success=false,$isdebug=''){
		header("Content-type:application/json; charset=utf-8");
		$jsondata = array(
				'success' => $success,
				'message' => $message,
				'data' => $data,
		);
		if (empty($status) && empty($data) && empty($message)) {
			$jsondata['message'] = '参数不能为空';
		}
		echo json_encode($jsondata);
		if (empty($isdebug)) {
			exit;
		}
	}
}


/**
 * 输出日志到文件
 */
if ( ! function_exists('log_output')) {
    function log_output($logData = '',$logFileName='')
    {
        $logStr = PHP_EOL.'------------'.date('Y-m-d H:i:s').'-------------'.PHP_EOL;
        $logStr .= var_export($logData,true);
        if($logFileName<>''){
            $logFileName = $logFileName.date('y-m-d').'.txt';
        }else{
            $logFileName = 'runLog'.date('y-m-d').'.txt';
        }
        file_put_contents(APPPATH.'logs/'.$logFileName, $logStr, FILE_APPEND);
    }
}


/**
 * 十六进制转字符串
 * @param $hex 16进制字符串
 * @return string
 */
if ( ! function_exists('hexToStr')) {
    function hexToStr($hex)
    {
        $string = "";
        for ($i = 0; $i < strlen($hex) - 1; $i += 2)
            $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
        return $string;
    }
}



/**
 * 获取当前毫秒数
 * @return float
 */
if ( ! function_exists('getMillisecond')) {
    function getMillisecond()
    {
        list($s1, $s2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
    }
}


/**
 * 接受数据
 * @author zxj
 * @access public
 * @param param mixed
 */
if ( ! function_exists('gp'))
{
    function gp($index=''){
        $CI =& get_instance();
        if(empty($index)){
            $method = $_SERVER['REQUEST_METHOD'];
            return $CI->input->$method()?$CI->input->$method():array();
        }
        return $CI->input->get_post($index);
    }
}


/***
 * 生成单号
 * @param string $prefix 唯一单号前缀
 * @return orderNumber
 */
if (!function_exists('build_order_no')) {
    function build_order_no($prefix = 'wx')
    {
        static $orderNumber = '';
        $CI =& get_instance();
        $CI->load->database();
        $orderNumber = $prefix . date('ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $cunt = $CI->db->query(sprintf("select count(`order_num`) as `cnt` from `mt_order` where `order_num` = '%s'", $orderNumber))->row_array();

        if (intval($cunt['cnt']) > 0) {
            build_order_no($prefix);
        }
        return $orderNumber;
    }
}



/**
 * 发送邮件
 * @params assign(email发送信息配置下标), emails(发送的邮箱), code(需要发送自定义额外的一些信息)
 * @example sendEmail(array('assign'=>'email_register','emails'=>'1006703013@qq.com','code'=>'mt_rand()'))
 * @param array $params
 * @return mixed
 */
if ( ! function_exists('sendEmail'))
{
    function sendEmail($params = array()){
        $CI =& get_instance();
        //加载邮件类和配置信息
        $CI->load->library('email');
        $CI->config->load('email');
        //发送邮件
        $smtp_user = $CI->config->item('smtp_user');
        $emailc = $CI->config->item($params['assign']);
        $CI->email->from($smtp_user, $emailc['email_name']);
        $CI->email->to($params['emails']);
        $CI->email->subject($emailc['email_title']);
        $CI->email->message(sprintf($emailc['email_content'],$params['code']));
        return $CI->email->send();
    }
}



/**
 * 创建目录
 * @author zxj
 * @access public
 * @param $dir 路径
 * @example mkdirs('div/css/layout/');
 */
if ( ! function_exists('mkdirs'))
{
	function mkdirs($dir){
		if(!is_dir($dir)){
			if(!mkdirs(dirname($dir))){
				return false;
			}
			if(!mkdir($dir, 0777)){
				return false;
			}
		}
		return true;
	}
}


/**
 * 删除目录以及目录下的文件
 * @author zxj
 * @access public
 * @param $dir 路径
 * @example deldirs('div/css/layout/');
 */
if ( ! function_exists('deldirs'))
{
	function deldirs($dir) {
		if (!is_dir($dir)) {
			return  false;
		}
		//先删除目录下的文件：
		$dh=opendir($dir);
		while ($file=readdir($dh)) {
			if($file!="." && $file!="..") {
				$fullpath=$dir."/".$file;
				if(!is_dir($fullpath)) {
					unlink($fullpath);
				} else {
					deldirs($fullpath);
				}
			}
		}
		closedir($dh);
		//删除当前文件夹：
		return rmdir($dir);
	}
}



/**
 * 删除文件
 * @author zxj
 * @access public
 * @param $dir 路径
 * @example delfile('div/css/layout/newfile.php');
 */
if ( ! function_exists('delfile'))
{
	function delfile($dir){
		return is_file($dir)?@unlink($dir):false;
	}
}


/**
 * 语言切换
 * @author zxj
 * @access public
 * @param $cutlang 需要切换的语言
 * @example <a href="<?=base_url(anewlang('english'))?>" >English</a>
 */
if ( ! function_exists('anewlang'))
{
	function anewlang($cutlang=''){
		if (config_item('enable_lang')) {
			$langList = array('sc','ch','english');
			$uriAry = explode('/', uri_string());
			$uriAry[0] = in_array($cutlang, $langList)?$cutlang:'english';
			$newuri = implode('/', $uriAry);
		}else{
			$newuri = uri_string();
		}
		return $newuri;
	}
}


/**
 * 带语言标识的URL
 * @author zxj
 * @access public
 * @example blang_url('uri');
 */
if ( ! function_exists('blang_url'))
{
	function blang_url($uri = '')
	{
		$CI =& get_instance();
		//$lang = config_item('language');
		$lang = $CI->config->item('language');
		return config_item('enable_lang')?base_url($lang.'/'.$uri):base_url($uri);
	}
}


/**
 * 转码
 * @author zxj
 * @access public
 * @example convertUTF8('str中文');
 */
if ( ! function_exists('convertUtf8'))
{
	function convertUtf8($str = '')
	{
		if(empty($str)) return '';
		return  iconv('gb2312', 'utf-8', $str);
	}
}


/**
 * PHP带消息的跳转
 * @param string $url
 * @param string $message
 * @param int $status_code
 * <meta http-equiv="refresh" charset="utf-8" content="3;url=<?=blang_url($goUrl)?>">
 */
if ( ! function_exists('show_goto'))
{
    function show_goto($goUrl = '',$message = '', $status_code = 200)
    {
        $heading = blang_url($goUrl);
        $_error =& load_class('Exceptions', 'core');
        echo $_error->show_error($heading, $message, 'error_goto', $status_code);
        exit;
    }
}

/**
 * 汇率转换
 * @param string $url
 * @param string $message
 * @param int $status_code
 * @param bool $is_ary
 *
 */
if ( ! function_exists('currency_service2')) {
    function currency_service2($fromCurrency = 'CNY',$toCurrency = 'USD',$amount = 0,$is_ary=false)
    {
        $url = 'http://apis.baidu.com/apistore/currencyservice/currency?fromCurrency='.$fromCurrency.'&toCurrency='.$toCurrency.'&amount=' . $amount;
        $ch = curl_init();
        $header = array(
            'apikey:ff5d69f75511ea262b064294d78b8202',
        );
        // 添加apikey到header
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        $res = curl_exec($ch);
        $resData = json_decode($res, true);
        $resData = $resData['retData'];
        return $is_ary?$resData:round($resData['convertedamount'], 3);
    }
}


/**
 * 汇率转换
 * @param string $url
 * @param string $message
 * @param int $status_code
 * @param bool $is_ary
 *
 */
if ( ! function_exists('currency_service3')) {
    function currency_service3($fromCurrency = 'CNY',$toCurrency = 'USD',$amount = 0,$is_ary=false)
    {
        $showapi_appid = '25594';  //替换此值,在官网的"我的应用"中找到相关值
        $showapi_secret = 'bc2d299faebf4712a9c2781716a517dc';  //替换此值,在官网的"我的应用"中找到相关值
        $paramArr = array(
            'showapi_appid'=> $showapi_appid, 'fromCode'=> $fromCurrency, 'toCode'=> $toCurrency, 'money'=> $amount
        );
        //创建参数
        $paraStr = "";
        $signStr = "";
        ksort($paramArr);
        foreach ($paramArr as $key => $val) {
            if ($key != '' && $val != '') {
                $signStr .= $key.$val;
                $paraStr .= $key.'='.urlencode($val).'&';
            }
        }
        $signStr .= $showapi_secret;//排好序的参数加上secret,进行md5
        $sign = strtolower(md5($signStr));
        $paraStr .= 'showapi_sign='.$sign;//将md5后的值作为参数,便于服务器的效验

        $url = 'http://route.showapi.com/105-31?'.$paraStr;
        $result = file_get_contents($url);
        $result = json_decode($result,true);
        if($is_ary){
            return $result;
        }else{
            return $result['showapi_res_body']['money'];
        }
    }
}

/**
 * 汇率转换
 * @param string $url
 * @param string $message
 * @param int $status_code
 * @param bool $is_ary
 *
 */
if ( ! function_exists('currency_service')) {
    function currency_service($fromCurrency = 'CNY',$toCurrency = 'USD',$amount = 0,$is_ary=false)
    {
        $codeArray = array(
            "$fromCurrency$toCurrency"
        );
        $codeStr=implode('","', $codeArray);
        $yql="select * from yahoo.finance.xchange where pair in (\"".  $codeStr."\")";
        $q=urlencode($yql);
        $url="https://query.yahooapis.com/v1/public/yql?q=".$q."&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,30);
        if(curl_exec($ch) === false)
        {
            echo 'Curl error: ' . curl_error($ch);
        }
        $response = curl_exec($ch);
        $responseObj=json_decode($response);
        $list=json_decode(json_encode($responseObj->query->results),TRUE);
        $list=$list['rate'];
        $rate = $list['Bid'];
        if($is_ary){
            return $list;
        }else{
            return $rate*$amount;
        }
    }
}


if ( ! function_exists('pushRule')) {
    function pushRule()
    {
        return array(
            '11' => array('vowney', 'p8000','p9000', 'p7000', 'm1', 'm2', 's2', 's2plus', 'p6000pro', 'trunk'),
            '4' => array('speed7', 'speed7plus')
        );
    }
}


if ( ! function_exists('pushRuleTax')) {
    function pushRuleTax($siteId = '')
    {
        $allTax =  array(
            '1'=>'0.21','3'=>'0.19','4'=>'0.2','5'=>'0.0884','2'=>'1'
        );
        return $allTax[$siteId]?$allTax[$siteId]:1;
    }
}



/**
 * URL重定向
 * @param $url
 * @param int $time
 * @param string $msg
 */
if ( ! function_exists('my_redirect')) {
    function my_redirect($url, $time = 0, $msg = '')
    {
        if (empty($msg))
            $msg = "系统将在{$time}秒之后自动跳转到{$url}!";
        if (!headers_sent()) {
            if (0 === $time) {
                header('Location: ' . $url);
            } else {
                header("refresh:{$time};url={$url}");
                echo($msg);
            }
            exit();
        } else {
            exit($url);
            $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
            if ($time != 0)
                $str .= $msg;
            exit($str);
        }
    }
}



/**
 * 执行跳转 JS
 * @author	zxj
 * @access	public
 * @param	gotourl(跳转地址),message(弹出信息),isback(是否后退)
 * @return	null
 */
if ( ! function_exists('js_goto'))
{
	function js_goto($gotourl,$message='',$isback=''){
		echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
		if ($isback && $message) {
			echo "<script>alert('$message');window.history.back(-1);</script>";
		}elseif ($isback){
			echo "<script>window.history.back(-1);</script>";
		}elseif ($gotourl && $message){
			echo "<script>alert('$message');location.href='$gotourl';</script>";
		}elseif ($gotourl){
			echo "<script>location.href='$gotourl';</script>";
		}elseif (empty($gotourl) && $message) {
			$gotourl = site_url();
			echo "<script>alert('$message');location.href='$gotourl';</script>";
		}else {
			$gotourl = site_url();
			echo "<script>location.href='$gotourl';</script>";
		}
		exit;
	}
}


/**
 * 格式化输出数组
 * @author zxj
 * @access public
 * @param param mixed $isdebug bool
 */
if ( ! function_exists('gsh_output')) {
    function gsh_output($param = '', $isdebug = false) {
        if(!headers_sent()){
            header('Content-type:text/html; charset=utf-8');
        }
        if (!$param) return false;
        echo "<pre style='margin-left:50px;;font-size:14px;color:#0000FF; '>";
        if (is_array($param)) {
            $countParam = count($param);
            echo '当前数组长度为:' . $countParam . '<br>';
            print_r($param);
        } else {
            echo "----------" . $param . "-------------";
        }
        echo "</pre>";
        if ($isdebug) exit;
    }
}


/**
 * 发送短信
 * @params  userNumber(接收人号码), codes(code码), strs(自定义字符串信息)
 * @example sendNote(array('usreNumber'=>'18520868129','codes'=>'****','strs'=>'您正在****请勿泄漏'))
 * @param array $params
 * @return mixed
 */
if ( ! function_exists('sendNote')) {
    function sendNote($params = array()) {
        $content = urlencode(iconv('UTF-8', 'GBK', $params['strs']));
        $url = 'http://gd.ums86.com:8899/sms/Api/Send.do';
        $data = 'SpCode=206702&LoginName=admin&Password=pel123&MessageContent=' . $content . '&UserNumber=' . $params['userNumber'] . '&SerialNumber=&ScheduleTime=&f=1';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if (!empty ($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}


/**
 * 导出Excel文档公共方法
 * @param $title(输出文件命名)
 * @param $fieldData(需要导出的字段和标题)
 * @param $excelData(需要导出的数据)
 * 输出到文件 $objWriter->save($outputFileName);
 */
if ( ! function_exists('excel_output')) {
    function excel_output($fileName, $fieldData, $excelData,$sheetTitle='') {
        if(empty($fieldData) || empty($excelData))
            gsh_output('需要导出的数据不完整，导出失败',1);
        //初始化CI
        $CI =& get_instance();
        //导入EXCEL类
        $CI->load->library('excel/PHPExcel');
        // 创建一个处理对象实例
        $objExcel = $CI->phpexcel;
        //设置当前的sheet索引，用于后续的内容操作。
        $objExcel->setActiveSheetIndex(0);
        $objActSheet = $objExcel->getActiveSheet();
        //设置当前活动sheet的名称
        $fileName = empty($fileName)?date('y-m-d H:i'):$fileName;
        $sheetTitle = empty($sheetTitle)?$fileName:$sheetTitle;
        $objActSheet->setTitle($sheetTitle);
        //将标题添加到数组中
        array_unshift($excelData,$fieldData);
        $letter='A';
        foreach ($fieldData as $key=>$val) {
            foreach ($excelData as $k=>$rs) {
                $objActSheet->setCellValue($letter.($k+1),$rs[$key]);
            }
            $letter++;
        }
        //输出文件
        $outputFileName = $fileName.'.xls';
        ob_end_clean();
        //将输出重定向到一个客户web浏览器
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $outputFileName . '"');
        header('Cache-Control: max-age=0');
        //如果你为IE 9,然后下面的可能需要
        header('Cache-Control: max-age=1');
        //如果你服务,即通过SSL,然后下面的可能需要
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');
        $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }
}


/**
 * 将excel文件数据转换为数组
 * @return array
 * @throws PHPExcel_Exception
 * @throws PHPExcel_Reader_Exception
 */
if ( ! function_exists('ExcelToArray')) {
    function ExcelToArray($files)
    {
        //导入EXCEL类
        $CI =& get_instance();
        //导入EXCEL类
        $CI->load->library('excel/PHPExcel');
        // 创建一个处理对象实例
        $objReader = $CI->phpexcel;
        $filetype = pathinfo($files, PATHINFO_EXTENSION);//获取后缀
        if ($filetype == 'xlsx') {
            $objReader = new PHPExcel_Reader_Excel2007();
        } else {
            $objReader = PHPExcel_IOFactory::createReader('Excel5');
        }
        // $objReader = PHPExcel_IOFactory::createReader('excel2007'); //use excel2007 for 2007 format
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($files);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow(); //总行数
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); //总列数
        $excelData = array();
        for ($i = 1; $i <= $highestRow; $i++) {
            $partRows = array();
            for ($j = 0; $j < $highestColumnIndex; $j++) {
                $gridVal = $objWorksheet->getCellByColumnAndRow($j, $i)->getValue();
                $partRows[] = $gridVal;
                //$partRows[] = $gridVal;
            }
            $excelData[] = $partRows;
        }
        foreach ($excelData as $k => $v) {
            if ($v[0] == '') {
                unset($excelData[$k]);
            }
        }
        return $excelData;
    }
}
/**
 * 文件上传方法
 * @param $file 上传文件
 * @param $uploaddir 路径
 * @param string $type 类型
 * @param string $size 大小
 * @return bool
 */
if ( ! function_exists('uploadfile')) {
    function uploadfile($file, $uploaddir, $type = '', $size = '')
    {
        set_time_limit(0);
        mkdirs($uploaddir);//这里需要先增加一个创建文件夹的模块
        $filetype = pathinfo($file['name'] , PATHINFO_EXTENSION);//获取后缀
        $uploadfile = $uploaddir . rand(10000 , 100000000000000000) . "." . $filetype;
        $y = 0;
        if ($type) {
            if (!in_array($filetype, $type)) {
                $y = 1;
                return 1;
            }
        }
        if ($size) {
            if ($file['size'] > $size) {
                $y = 1;
                return 2;
            }
        }
        if ($y == 0) {
            //开始移动PHP上传的临时文件到当前目录下
            $shangchuan=move_uploaded_file($file['tmp_name'],$uploadfile);
            if($shangchuan){
                return str_replace('./',base_url(),$uploadfile);
            }
        }
    }
}

/**
 * 返回页码且当前页居中
 * @param $page(当前页)$total(总页数)$links(页面显示多少条)
 * @example pageCenter($page,$totalPage,10)
 * @return $pageShow(array 页码数组)
 */
if ( ! function_exists('pages_center'))
{
	function pages_center($page,$total,$links=5){
		$pageShow = array();
		if($total>0 && $total<=$links){
			for($i=1;$i<=$total;$i++){
				$pageShow[]=$i;
			}
		}
		if($total>$links){
			$centerNum = ceil($links/2);  //居中数
			if($page<=$centerNum){
				for($i=1;$i<=$links;$i++){
					$pageShow[]=$i;
				}
			}
			if ($page>$total-$centerNum) {
				for ($i=$total-$links+1;$i<=$total;$i++) {
					$pageShow[] = $i;
				}
			}
			if($page>$centerNum && $page<=$total-$centerNum){
				$start = $page-$centerNum+1;
				$end = $links%2==0?$page+$centerNum:$page+$centerNum-1;
				for($j=$start;$j<=$end;$j++){
					$pageShow[]=$j;
				}
			}
		}
		return $pageShow;
	}
}

/**
 * 获取速卖通API URL
 * @param string $apiInfo(api函数地址)
 * @param string $code_arr(api查询条件参数)
 */
if( ! function_exists('getAliExpressSign')){
    function getAliExpressSign($apiInfo_str='',$code_arr=''){
        $url = 'http://gw.api.alibaba.com:80/openapi/';//1688开放平台使用gw.open.1688.com域名
        $appKey = '9131907';;
        $appSecret ='LSOxdb16FHQ';
        /*$apiInfo = 'param2/1/aliexpress.open/alibaba.ae.warrantie.getList/' . $appKey;//此处请用具体api进行替换
        //配置参数，请用apiInfo对应的api参数进行替换
        $code_arr = array(
            'supplierId'=>'pandawill',
            'startBuyTime' => '2015-01-02 00:00:00',
            'endBuyTime' => '2016-01-02 00:00:00'
        );*/
        $info='param2/1/aliexpress.open/';
        $apiInfo=$info.$apiInfo_str.'/'.$appKey;
        $aliParams = array();
        $param_str='';//连接参数
        foreach ($code_arr as $key => $val) {
            $aliParams[] = $key . $val;
            $param_str .= $key . '=' . urlencode($val) . '&';
        }
        sort($aliParams);
        $sign_str = join('', $aliParams);
        $sign_str = $apiInfo . $sign_str;
        $code_sign = strtoupper(bin2hex(hash_hmac("sha1", $sign_str, $appSecret, true)));
        $apiurl=$url.$apiInfo.'?'.$param_str.'_aop_signature='.$code_sign;
        return $apiurl;
    }
}
/**
 * urlget
 * @param $url
 * @return mixed
 */
if( ! function_exists('UrlGet')){
    function UrlGet($url){
        //初始化
        $ch = curl_init();

        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);

        //释放curl句柄
        curl_close($ch);
        //打印获得的数据
        return json_decode($output,true);
    }
}
/**
 * CurlPost
 */
if ( ! function_exists('CurlPost')) {
    function CurlPost($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
        curl_setopt($ch, CURLOPT_URL, $url);
        $response=curl_exec($ch);
        curl_close($ch);
        $result = json_decode($response,true);
        return $result;
    }
}

/**
 * TomRepairCurlPost
 */
if ( ! function_exists('TomRepairCurlPost')) {
    function TomRepairCurlPost($url,$data){
        // Initialize cURL
        $curl = curl_init();
        $headers = array();
        $headers[] = 'Authorization: DMCOHh3Y6Zf562MaDU3YzMyRjp3RFP9987trzdLZRZzcjFt';
        $headers[] = 'Content-Type: application/json; charset=utf-8';
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_BINARYTRANSFER,true);
        curl_setopt($curl,CURLOPT_URL, $url);
        curl_setopt($curl,CURLOPT_POST, sizeof($data));
        curl_setopt($curl,CURLOPT_POSTFIELDS, json_encode($data));
        $result = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($result,true);
        return $result;
    }
}
/**
 * 获取包裹序号
 * @param $num
 */
if ( ! function_exists('GetPackageNo')) {
    function GetPackageNo($num){
        $charActors = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
        return $charActors[$num];
    }
}

if ( ! function_exists('ExportCsv')) {
    /**
     * 导出CSV文件
     * @param array $data
     * @param array $header_data
     * @param string $file_name
     */
    function  ExportCsv($data = array(), $header_data = array(), $file_name = '')
    {
        //将输出重定向到一个客户web浏览器
        header ( "Content-type:application/vnd.ms-excel;charset=utf-8" );
        header('Content-Disposition: attachment;filename="' . $file_name . '.csv"');
        header('Cache-Control: max-age=0');
        /*//如果你为IE 9,然后下面的可能需要
        header('Cache-Control: max-age=1');
        //如果你服务,即通过SSL,然后下面的可能需要
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');*/
        $fp = fopen('php://output', 'a');
        if (!empty($header_data)) {
            foreach ($header_data as $key => $value) {
                $header_data[$key] = iconv('utf-8', 'gbk', $value);
            }
        }
        fputcsv($fp, $header_data);
        $num = 0;
        //每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
        $limit = 1000;
        //逐行取出数据，不浪费内存
        $count = count($data);
        if ($count > 0) {
            for ($i = 0; $i < $count; $i++) {
                $num++;
                //刷新一下输出buffer，防止由于数据过多造成问题
                if ($limit == $num) {
                    ob_flush();
                    flush();
                    $num = 0;
                }
                $row = $data[$i];
                foreach ($row as $key => $value) {
                    $row[$key] = iconv('utf-8', 'gbk', $value);
                }
                fputcsv($fp, $row);
            }
        }
        fclose($fp);
    }
}
if ( ! function_exists('array_column')) {
    /**
     * 替代低版本（5.5以下）不存在array_column函数的问题
     */
    function array_column($input, $columnKey, $indexKey = NULL)
    {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? TRUE : FALSE;
        $indexKeyIsNull = (is_null($indexKey)) ? TRUE : FALSE;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? TRUE : FALSE;
        $result = array();

        foreach ((array) $input AS $key => $row)
        {
            if ($columnKeyIsNumber)
            {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : NULL;
            }
            else
            {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : NULL;
            }
            if (!$indexKeyIsNull)
            {
                if ($indexKeyIsNumber)
                {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && !empty($key)) ? current($key) : NULL;
                    $key = is_null($key) ? 0 : $key;
                }
                else
                {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }

            $result[$key] = $tmp;
        }

        return $result;
    }
}

if (!function_exists('GetInitial')) {
    function GetInitial($str)
    {
        $firstchar_ord = ord(strtoupper($str{0}));
        if (($firstchar_ord >= 65 and $firstchar_ord <= 91) or ($firstchar_ord >= 48 and $firstchar_ord <= 57))
            return $str{0};
        $s = iconv("UTF-8" , "gb2312" , $str);
        $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
        if ($asc >= -20319 and $asc <= -20284)
            return "A";
        if ($asc >= -20283 and $asc <= -19776)
            return "B";
        if ($asc >= -19775 and $asc <= -19219)
            return "C";
        if ($asc >= -19218 and $asc <= -18711)
            return "D";
        if ($asc >= -18710 and $asc <= -18527)
            return "E";
        if ($asc >= -18526 and $asc <= -18240)
            return "F";
        if ($asc >= -18239 and $asc <= -17923)
            return "G";
        if ($asc >= -17922 and $asc <= -17418)
            return "H";
        if ($asc >= -17417 and $asc <= -16475)
            return "J";
        if ($asc >= -16474 and $asc <= -16213)
            return "K";
        if ($asc >= -16212 and $asc <= -15641)
            return "L";
        if ($asc >= -15640 and $asc <= -15166)
            return "M";
        if ($asc >= -15165 and $asc <= -14923)
            return "N";
        if ($asc >= -14922 and $asc <= -14915)
            return "O";
        if ($asc >= -14914 and $asc <= -14631)
            return "P";
        if ($asc >= -14630 and $asc <= -14150)
            return "Q";
        if ($asc >= -14149 and $asc <= -14091)
            return "R";
        if ($asc >= -14090 and $asc <= -13319)
            return "S";
        if ($asc >= -13318 and $asc <= -12839)
            return "T";
        if ($asc >= -12838 and $asc <= -12557)
            return "W";
        if ($asc >= -12556 and $asc <= -11848)
            return "X";
        if ($asc >= -11847 and $asc <= -11056)
            return "Y";
        if ($asc >= -11055 and $asc <= -10247)
            return "Z";
        return null;
    }
}
if (!function_exists('ArraySort')) {
    /**
     * @param $arrays 排序的数组
     * @param $sort_key 需要排序的键
     * @param int $sort_order SORT_ASC - 默认，按升序排列。(A-Z) SORT_DESC - 按降序排列。(Z-A)
     * @param int $sort_type SORT_REGULAR - 默认。将每一项按常规顺序排列。  SORT_NUMERIC - 将每一项按数字顺序排列。  SORT_STRING - 将每一项按字母顺序排列
     * @return bool
     */
    function ArraySort($arrays , $sort_key , $sort_order = SORT_ASC , $sort_type = SORT_NUMERIC)
    {
        if (is_array($arrays)) {
            foreach ($arrays as $array) {
                if (is_array($array)) {
                    $key_arrays[] = $array[$sort_key];
                }
                else {
                    return false;
                }
            }
        }
        else {
            return false;
        }
        array_multisort($key_arrays , $sort_order , $sort_type , $arrays);
        return $arrays;
    }
}
